<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png?v=7.4.0">
  <link rel="mask-icon" href="/images/avatar.svg?v=7.4.0" color="#222">
  <link rel="alternate" href="/atom.xml" title="Anemone's Blog" type="application/atom+xml">
  <meta name="google-site-verification" content="Re5JdegRYzNFco-rC9lYIsvSWIgh5JvyfhuEaZCeFCk">
  <meta name="baidu-site-verification" content="opTC8YN3Pn">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: 'GB90MXPJ1C',
      apiKey: '05d808da3baf50ac2f2fad2dc3a3cd8f',
      indexName: 'dev_blog',
      hits: {"per_page":20},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":true,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="遗传算法是求解近似最优解的最具代表性的智能算法之一，如今的很多方法都可以看到它的影子，比如说之前在研究的基于覆盖率的fuzz测试，其中的输入变异就类似于遗传算法，故从旧博客搬运来。简介遗传算法在外部体现同模拟退火一样,也是属于优化问题的一个求解器.但由于其优异的收敛速度和比模拟退火更优秀的结果,在对结果要求高的题目上,它也成为我们求解问题的常用方法.">
<meta name="keywords" content="算法,人工智能">
<meta property="og:type" content="article">
<meta property="og:title" content="遗传算法——另一个求最优解的智能算法">
<meta property="og:url" content="http://anemone.top/数模-遗传算法——另一个求最优解的智能算法/index.html">
<meta property="og:site_name" content="Anemone&#39;s Blog">
<meta property="og:description" content="遗传算法是求解近似最优解的最具代表性的智能算法之一，如今的很多方法都可以看到它的影子，比如说之前在研究的基于覆盖率的fuzz测试，其中的输入变异就类似于遗传算法，故从旧博客搬运来。简介遗传算法在外部体现同模拟退火一样,也是属于优化问题的一个求解器.但由于其优异的收敛速度和比模拟退火更优秀的结果,在对结果要求高的题目上,它也成为我们求解问题的常用方法.">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://anemone.top/数模-遗传算法——另一个求最优解的智能算法/ga-1545742951220.jpg">
<meta property="og:image" content="http://anemone.top/数模-遗传算法——另一个求最优解的智能算法/graph.jpg">
<meta property="og:updated_time" content="2019-09-22T10:14:18.782Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="遗传算法——另一个求最优解的智能算法">
<meta name="twitter:description" content="遗传算法是求解近似最优解的最具代表性的智能算法之一，如今的很多方法都可以看到它的影子，比如说之前在研究的基于覆盖率的fuzz测试，其中的输入变异就类似于遗传算法，故从旧博客搬运来。简介遗传算法在外部体现同模拟退火一样,也是属于优化问题的一个求解器.但由于其优异的收敛速度和比模拟退火更优秀的结果,在对结果要求高的题目上,它也成为我们求解问题的常用方法.">
<meta name="twitter:image" content="http://anemone.top/数模-遗传算法——另一个求最优解的智能算法/ga-1545742951220.jpg">
  <link rel="canonical" href="http://anemone.top/数模-遗传算法——另一个求最优解的智能算法/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>遗传算法——另一个求最优解的智能算法 | Anemone's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Anemone's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-about">
      
    

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="fa fa-search fa-fw"></i>搜索</a>
      </li>
    
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input" id="search-input"></div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="algolia-results">
  <div id="algolia-stats"></div>
  <div id="algolia-hits"></div>
  <div id="algolia-pagination" class="algolia-pagination"></div>
</div>

  
</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="http://anemone.top/数模-遗传算法——另一个求最优解的智能算法/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Anemone">
      <meta itemprop="description" content="关注Web安全、移动安全、Fuzz测试和机器学习">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Anemone's Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">遗传算法——另一个求最优解的智能算法

          
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2016-02-09 20:27:49" itemprop="dateCreated datePublished" datetime="2016-02-09T20:27:49+08:00">2016-02-09</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-09-22 18:14:18" itemprop="dateModified" datetime="2019-09-22T18:14:18+08:00">2019-09-22</time>
              </span>
            
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/数学建模/" itemprop="url" rel="index"><span itemprop="name">数学建模</span></a></span>

                
                
              
            </span>
          

          
            <span id="/数模-遗传算法——另一个求最优解的智能算法/" class="post-meta-item leancloud_visitors" data-flag-title="遗传算法——另一个求最优解的智能算法" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>遗传算法是求解近似最优解的最具代表性的智能算法之一，如今的很多方法都可以看到它的影子，比如说之前在研究的基于覆盖率的fuzz测试，其中的输入变异就类似于遗传算法，故从旧博客搬运来。</p><h1 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h1><p>遗传算法在外部体现同模拟退火一样,也是属于优化问题的一个求解器.但由于其优异的收敛速度和比模拟退火更优秀的结果,在对结果要求高的题目上,它也成为我们求解问题的常用方法.</p><a id="more"></a>

<p><img src="/数模-遗传算法——另一个求最优解的智能算法/ga-1545742951220.jpg" alt="ga"></p>
<h1 id="快速使用"><a href="#快速使用" class="headerlink" title="快速使用"></a>快速使用</h1><p>遗传算法在实现上比模拟退火要复杂很多,但若不关心其内部算法,使用上反而比模拟退火要简单.</p>
<h2 id="连续型随机变量"><a href="#连续型随机变量" class="headerlink" title="连续型随机变量"></a>连续型随机变量</h2><p><strong>案例一:</strong>求<code>min(x^2+y^2),x,y∈[-1e5,1e5]</code>:</p>
<ol>
<li><p>复制<code>GANorm</code>文件夹到你的工作目录.</p>
</li>
<li><p>同文件夹下新建<code>demo.m</code>文件,输入:</p>
 <figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">y=@(x)x(<span class="number">1</span>)^<span class="number">2</span>+x(<span class="number">2</span>)^<span class="number">2</span>;</span><br><span class="line">[best,x]=EzGA([<span class="number">-1e5</span> <span class="number">1e5</span>;<span class="number">-1e5</span> <span class="number">1e5</span>],y)</span><br></pre></td></tr></table></figure>
</li>
<li><p>运行<code>demo.m</code>文件,得到从运行及结果:</p>
 <figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">sizepop =</span><br><span class="line">        <span class="number">1000</span></span><br><span class="line">best =</span><br><span class="line">    <span class="number">3.9901</span></span><br><span class="line">x =</span><br><span class="line">    <span class="number">1.9975</span>   <span class="number">-0.0001</span></span><br></pre></td></tr></table></figure>
<p> 没错,简单的遗传算法函数的调用形式为EzGA(变量上下限,目标函数句柄[,初始种群数量=500,附加数据]),注意第三个,第四个变量为可选参数.</p>
</li>
</ol>
<p><strong>案例二:</strong>求<code>min(0.7*x(1)+0.8*x(2)),x,y∈[-1e5,1e5]</code>:</p>
<ol>
<li><p>复制<code>GANorm</code>文件夹到你的工作目录.</p>
</li>
<li><p>同文件夹下新建<code>demo2.m</code>文件,输入:</p>
 <figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[best,x]=EzGA([<span class="number">-1e5</span> <span class="number">1e5</span>;<span class="number">-1e5</span> <span class="number">1e5</span>],@OptFun,<span class="number">1e2</span>,[<span class="number">0.7</span> <span class="number">0.8</span>])</span><br></pre></td></tr></table></figure>
</li>
<li><p>同文件夹下新建<code>OptFun.m</code>文件,输入:</p>
 <figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">y</span>=<span class="title">OptFun</span><span class="params">(x,coe)</span></span></span><br><span class="line">    y=coe(<span class="number">1</span>)*x(<span class="number">1</span>)^<span class="number">2</span>+coe(<span class="number">2</span>)*x(<span class="number">2</span>)^<span class="number">2</span>;</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>运行<code>demo2.m</code>文件,得到从运行及结果:</p>
 <figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">sizepop =</span><br><span class="line">   <span class="number">100</span></span><br><span class="line">best =</span><br><span class="line">   <span class="number">1.1761e-07</span></span><br><span class="line">x =</span><br><span class="line">   <span class="number">1.0e-03</span> *</span><br><span class="line">   <span class="number">-0.0079</span>    <span class="number">0.3834</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h1 id="原理讲解"><a href="#原理讲解" class="headerlink" title="原理讲解"></a>原理讲解</h1><p>以下结合案例,来解释一下遗传算法的具体实现.</p>
<h2 id="连续型随机变量-TSP问题"><a href="#连续型随机变量-TSP问题" class="headerlink" title="连续型随机变量(TSP问题)"></a>连续型随机变量(TSP问题)</h2><p>下面又是我们的旅行商问题,同样,我们有图(*代表城镇):<br><img src="/数模-遗传算法——另一个求最优解的智能算法/graph.jpg" alt="graph"></p>
<p>首先,结合流程图,我们首先写主函数调用遗传算法<code>GATSP</code><br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">%记录了城镇的坐标</span></span><br><span class="line">X=[</span><br><span class="line"><span class="number">16.47</span>,<span class="number">96.10</span></span><br><span class="line"><span class="number">16.47</span>,<span class="number">94.44</span></span><br><span class="line"><span class="number">20.09</span>,<span class="number">92.54</span></span><br><span class="line"><span class="number">22.39</span>,<span class="number">93.37</span></span><br><span class="line"><span class="number">25.23</span>,<span class="number">97.24</span></span><br><span class="line"><span class="number">22.00</span>,<span class="number">96.05</span></span><br><span class="line"><span class="number">20.47</span>,<span class="number">97.02</span></span><br><span class="line"><span class="number">17.29</span>,<span class="number">96.29</span></span><br><span class="line"><span class="number">16.30</span>,<span class="number">97.38</span></span><br><span class="line"><span class="number">14.05</span>,<span class="number">98.12</span></span><br><span class="line"><span class="number">16.53</span>,<span class="number">97.38</span></span><br><span class="line"><span class="number">21.52</span>,<span class="number">95.59</span></span><br><span class="line"><span class="number">20.09</span>,<span class="number">92.55</span>];</span><br><span class="line">D=Distance(X); <span class="comment">%取得邻接矩阵</span></span><br><span class="line">N=<span class="built_in">size</span>(D,<span class="number">1</span>);    <span class="comment">%城镇数</span></span><br><span class="line"><span class="comment">%调用遗传算法</span></span><br><span class="line">[obj,x]=GATSP(N,D);</span><br></pre></td></tr></table></figure></p>
<p>遗传算法主函数:<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="params">[minObj,x]</span>=<span class="title">GATSP</span><span class="params">(N,attach,NIND)</span></span></span><br><span class="line"></span><br><span class="line">    MAXGEN=<span class="number">200</span>;</span><br><span class="line">    <span class="keyword">if</span> nargin&lt;<span class="number">3</span></span><br><span class="line">        NIND=<span class="number">100</span>;</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    Pc=<span class="number">0.9</span>;</span><br><span class="line">    Pm=<span class="number">0.2</span>;</span><br><span class="line">    GGAP=<span class="number">0.9</span>;</span><br><span class="line"></span><br><span class="line">    Chrom=InitPop(NIND,N);</span><br><span class="line">    <span class="comment">% Rlength=PathLength(D,Chrom(1,:));</span></span><br><span class="line">    gen=<span class="number">0</span>;</span><br><span class="line">    <span class="comment">% ObjV=PathLength(D,Chrom);</span></span><br><span class="line">    <span class="comment">% preObjV=min(ObjV);</span></span><br><span class="line">    history=[];</span><br><span class="line">    h=waitbar(<span class="number">0</span>,<span class="string">'Evolving....'</span>);</span><br><span class="line">    <span class="keyword">while</span> gen&lt;MAXGEN</span><br><span class="line">        ObjV=PathLength(attach,Chrom);</span><br><span class="line">    <span class="comment">%    min(ObjV)</span></span><br><span class="line">        FitnV=Fitness(ObjV);</span><br><span class="line">        SelCh=Select(Chrom,FitnV,GGAP);</span><br><span class="line">        SelCh=Recombin(SelCh,Pc);</span><br><span class="line">        SelCh=Mutate(SelCh,Pm);</span><br><span class="line">        SelCh=Reverse(SelCh,attach);</span><br><span class="line">        Chrom=Reins(Chrom,SelCh,ObjV);</span><br><span class="line">        history=[history <span class="built_in">min</span>(ObjV)];</span><br><span class="line">        gen=gen+<span class="number">1</span>;</span><br><span class="line">        waitbar(gen/MAXGEN,h,sprintf(<span class="string">'Now Generation:%d'</span>,gen));</span><br><span class="line">        <span class="keyword">if</span> gen&gt;<span class="number">30</span></span><br><span class="line">            <span class="keyword">if</span> sum(diff(history(<span class="keyword">end</span><span class="number">-30</span>:<span class="keyword">end</span>)))==<span class="number">0</span></span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            <span class="keyword">end</span></span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    close(h)</span><br><span class="line"></span><br><span class="line">    ObjV=PathLength(attach,Chrom);</span><br><span class="line">    <span class="built_in">plot</span>(history)</span><br><span class="line">    title(<span class="string">'Fitness curve'</span>,<span class="string">'fontsize'</span>,<span class="number">12</span>);</span><br><span class="line">    xlabel(<span class="string">'Evolutionary generation'</span>,<span class="string">'fontsize'</span>,<span class="number">12</span>);ylabel(<span class="string">'Option'</span>,<span class="string">'fontsize'</span>,<span class="number">12</span>);</span><br><span class="line">    <span class="comment">% axis([0,MAXGEN,0,1])</span></span><br><span class="line"></span><br><span class="line">    [minObj,minInd]=<span class="built_in">min</span>(ObjV);</span><br><span class="line">    x=Chrom(minInd,:);</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure></p>
<h2 id="初始化种群"><a href="#初始化种群" class="headerlink" title="初始化种群"></a>初始化种群</h2><p>初始化种群实际就是产生NIND个符合要求的解.<code>InitPop.m</code>:<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Chrom</span>=<span class="title">InitPop</span><span class="params">(NIND,N)</span></span></span><br><span class="line">    <span class="comment">%NIND 种群大小</span></span><br><span class="line">    <span class="comment">%N 单个染色体长度(城市个数)</span></span><br><span class="line">    Chrom=<span class="built_in">zeros</span>(NIND,N);</span><br><span class="line">    <span class="keyword">for</span> <span class="built_in">i</span>=<span class="number">1</span>:NIND</span><br><span class="line">        Chrom(<span class="built_in">i</span>,:)=randperm(N); <span class="comment">%随机产生种群</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure></p>
<h2 id="适应度函数"><a href="#适应度函数" class="headerlink" title="适应度函数"></a>适应度函数</h2><p>TSP的要求是路程最短,而适应度函数视值越大越优,所以我们这里先计算出长度后,再对其取反.</p>
<p><code>PathLength.m</code>:<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">len</span>=<span class="title">PathLength</span><span class="params">(graph,Chrom)</span></span></span><br><span class="line">    [row,col]=<span class="built_in">size</span>(graph);</span><br><span class="line">    NIND=<span class="built_in">size</span>(Chrom,<span class="number">1</span>);</span><br><span class="line">    len=<span class="built_in">zeros</span>(NIND,<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">for</span> <span class="built_in">i</span>=<span class="number">1</span>:NIND</span><br><span class="line">        <span class="comment">% path</span></span><br><span class="line">        p=[Chrom(<span class="built_in">i</span>,:) Chrom(<span class="built_in">i</span>,<span class="number">1</span>)];</span><br><span class="line">        i1=p(<span class="number">1</span>:<span class="keyword">end</span><span class="number">-1</span>);</span><br><span class="line">        i2=p(<span class="number">2</span>:<span class="keyword">end</span>);</span><br><span class="line">        len(<span class="built_in">i</span>,<span class="number">1</span>)=sum(graph((i1<span class="number">-1</span>)*col+i2));<span class="comment">% ∑graph(from,to)</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure></p>
<p><code>Fitness.m</code>:<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">FitnV</span>=<span class="title">Fitness</span><span class="params">(len)</span></span></span><br><span class="line">    <span class="comment">% len 个体长度</span></span><br><span class="line">    FitnV=<span class="number">1.</span>/len;</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure></p>
<h2 id="选择操作"><a href="#选择操作" class="headerlink" title="选择操作"></a>选择操作</h2><p>模拟自然选择,实际上就是指适应度越好的解被留下来的几率越大(但也不是说适应度不好的解不被留下).<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SelCh</span>=<span class="title">Select</span><span class="params">(Chrom,FitnV,GGAP)</span></span></span><br><span class="line">    <span class="comment">%种群 适应值 选择概率 被选择个体</span></span><br><span class="line">    NIND=<span class="built_in">size</span>(Chrom,<span class="number">1</span>);</span><br><span class="line">    NSel=<span class="built_in">max</span>(<span class="built_in">floor</span>(NIND*GGAP+<span class="number">0.5</span>),<span class="number">2</span>);</span><br><span class="line">    Chrlx=Sus(FitnV,NSel);</span><br><span class="line">    SelCh=Chrom(Chrlx,:);</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">NewChrlx</span>=<span class="title">Sus</span><span class="params">(FitnV,NSel)</span></span></span><br><span class="line">    <span class="comment">%适应值 数目</span></span><br><span class="line">    <span class="comment">%备选索引</span></span><br><span class="line">    [Nind,ans_]=<span class="built_in">size</span>(FitnV);</span><br><span class="line">    cumfit=cumsum(FitnV);</span><br><span class="line">    trials=cumfit(Nind)/NSel*(<span class="built_in">rand</span>+(<span class="number">0</span>:NSel<span class="number">-1</span>)');</span><br><span class="line">    Mf=cumfit(:,<span class="built_in">ones</span>(<span class="number">1</span>,NSel));</span><br><span class="line">    Mt=trials(:,<span class="built_in">ones</span>(<span class="number">1</span>,Nind))';</span><br><span class="line">    [NewChrlx,ans_]=<span class="built_in">find</span>(Mt&lt;Mf&amp;[<span class="built_in">zeros</span>(<span class="number">1</span>,NSel);Mf(<span class="number">1</span>:Nind<span class="number">-1</span>,:)]&lt;=Mt);</span><br><span class="line">    [ans_,shuf]=<span class="built_in">sort</span>(<span class="built_in">rand</span>(NSel,<span class="number">1</span>));</span><br><span class="line">    NewChrlx=NewChrlx(shuf);</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure></p>
<h2 id="交叉操作"><a href="#交叉操作" class="headerlink" title="交叉操作"></a>交叉操作</h2><p>模拟染色体的交叉现象,注意在这里会出现城市出现重复的现象,需要用部分映射的方法消除冲突(介于篇幅不赘述,但我就记得这问题我想了一下午,然后一个数科院的妹子3分钟搞定了.顿时就感觉!!).<br>原先的两个解:<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">| <span class="number">9</span>, <span class="number">5</span>, <span class="number">1</span>| <span class="number">3</span>, <span class="number">7</span>, <span class="number">4</span>, <span class="number">2</span>| <span class="number">10</span>, <span class="number">8</span>, <span class="number">6</span>|</span><br><span class="line">|--------|-----------|---------|</span><br><span class="line">|<span class="number">10</span>, <span class="number">5</span>, <span class="number">4</span>| <span class="number">6</span>, <span class="number">3</span>, <span class="number">8</span>, <span class="number">7</span>|  <span class="number">2</span>, <span class="number">1</span>, <span class="number">9</span>|</span><br></pre></td></tr></table></figure></p>
<p>交叉<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">| <span class="number">9</span>, <span class="number">5</span>, <span class="number">1</span>| <span class="number">6</span>, <span class="number">3</span>, <span class="number">8</span>, <span class="number">7</span>| <span class="number">10</span>, *, *|</span><br><span class="line">|--------|-----------|---------|</span><br><span class="line">|<span class="number">10</span>, <span class="number">5</span>, *| <span class="number">3</span>, <span class="number">7</span>, <span class="number">4</span>, <span class="number">2</span>|  *, <span class="number">1</span>, <span class="number">9</span>|</span><br></pre></td></tr></table></figure></p>
<p>部分映射<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">| <span class="number">9</span>, <span class="number">5</span>, <span class="number">1</span>| <span class="number">6</span>, <span class="number">3</span>, <span class="number">8</span>, <span class="number">7</span>| <span class="number">10</span>, <span class="number">4</span>, <span class="number">2</span>|</span><br><span class="line">|--------|-----------|---------|</span><br><span class="line">|<span class="number">10</span>, <span class="number">5</span>, <span class="number">8</span>| <span class="number">3</span>, <span class="number">7</span>, <span class="number">4</span>, <span class="number">2</span>|  <span class="number">6</span>, <span class="number">1</span>, <span class="number">9</span>|</span><br></pre></td></tr></table></figure></p>
<p><code>Recombin.m</code>:<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SelCh</span>=<span class="title">Recombin</span><span class="params">(SelCh,Pc)</span></span></span><br><span class="line">    <span class="comment">%被选择个体 概率</span></span><br><span class="line">    <span class="comment">%交叉后个体</span></span><br><span class="line">    NSel=<span class="built_in">size</span>(SelCh,<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">for</span> <span class="built_in">i</span>=<span class="number">1</span>:<span class="number">2</span>:NSel-<span class="built_in">mod</span>(NSel,<span class="number">2</span>)</span><br><span class="line">        <span class="keyword">if</span> Pc&gt;=<span class="built_in">rand</span></span><br><span class="line">            [SelCh(<span class="built_in">i</span>,:),SelCh(<span class="built_in">i</span>+<span class="number">1</span>,:)]=intercross(SelCh(<span class="built_in">i</span>,:),SelCh(<span class="built_in">i</span>+<span class="number">1</span>,:));</span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="params">[a,b]</span>=<span class="title">intercross</span><span class="params">(a,b)</span></span></span><br><span class="line">    L=<span class="built_in">length</span>(a);</span><br><span class="line">    r1=randsrc(<span class="number">1</span>,<span class="number">1</span>,[<span class="number">1</span>,L]);</span><br><span class="line">    r2=randsrc(<span class="number">1</span>,<span class="number">1</span>,[<span class="number">1</span>,L]);</span><br><span class="line">    <span class="keyword">if</span> r1~=r2</span><br><span class="line">        a0=a;b0=b;</span><br><span class="line">        s=<span class="built_in">min</span>([r1,r2]);</span><br><span class="line">        e=<span class="built_in">max</span>([r1,r2]);</span><br><span class="line">        <span class="keyword">for</span> <span class="built_in">i</span>=s:e</span><br><span class="line">            a1=a;b1=b;</span><br><span class="line">            a(<span class="built_in">i</span>)=b0(<span class="built_in">i</span>);</span><br><span class="line">            b(<span class="built_in">i</span>)=a0(<span class="built_in">i</span>);</span><br><span class="line">            x=<span class="built_in">find</span>(a==a(<span class="built_in">i</span>));</span><br><span class="line">            y=<span class="built_in">find</span>(b==b(<span class="built_in">i</span>));</span><br><span class="line">            i1=x(x~=<span class="built_in">i</span>);</span><br><span class="line">            i2=y(y~=<span class="built_in">i</span>);</span><br><span class="line">            <span class="keyword">if</span> ~<span class="built_in">isempty</span>(i1)</span><br><span class="line">                a(i1)=a1(<span class="built_in">i</span>);</span><br><span class="line">            <span class="keyword">end</span></span><br><span class="line">            <span class="keyword">if</span> ~<span class="built_in">isempty</span>(i2)</span><br><span class="line">                b(i2)=b1(<span class="built_in">i</span>);</span><br><span class="line">            <span class="keyword">end</span></span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure></p>
<h2 id="变异操作"><a href="#变异操作" class="headerlink" title="变异操作"></a>变异操作</h2><p>模拟染色体的变异现象,这里的算子就是两个随机位置上的数交换<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">| <span class="number">9</span>, <span class="number">5</span>, <span class="number">1</span>| <span class="number">3</span>, <span class="number">7</span>, <span class="number">4</span>, <span class="number">2</span>| <span class="number">10</span>, <span class="number">8</span>, <span class="number">6</span>|</span><br><span class="line">| <span class="number">9</span>, <span class="number">5</span>, <span class="number">2</span>| <span class="number">3</span>, <span class="number">7</span>, <span class="number">4</span>, <span class="number">1</span>| <span class="number">10</span>, <span class="number">8</span>, <span class="number">6</span>|</span><br></pre></td></tr></table></figure></p>
<p><code>Mutate.m</code>:<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SelCh</span>=<span class="title">Mutate</span><span class="params">(SelCh,Pm)</span></span></span><br><span class="line">    <span class="comment">%个体 概率</span></span><br><span class="line">    [NSel,L]=<span class="built_in">size</span>(SelCh);</span><br><span class="line">    <span class="keyword">for</span> <span class="built_in">i</span>=<span class="number">1</span>:NSel</span><br><span class="line">        <span class="keyword">if</span> Pm&gt;=<span class="built_in">rand</span></span><br><span class="line">            R=randperm(L);</span><br><span class="line">            SelCh(<span class="built_in">i</span>,R(<span class="number">1</span>:<span class="number">2</span>))=SelCh(<span class="built_in">i</span>,R(<span class="number">2</span>:<span class="number">-1</span>:<span class="number">1</span>));</span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure></p>
<h2 id="重组"><a href="#重组" class="headerlink" title="重组"></a>重组</h2><p>就是把经过选择,交叉,变异的解与旧解混合,保证种群内个体数不变.<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Chrom</span>=<span class="title">Reins</span><span class="params">(Chrom,SelCh,ObjV)</span></span></span><br><span class="line">    NIND=<span class="built_in">size</span>(Chrom,<span class="number">1</span>);</span><br><span class="line">    NSel=<span class="built_in">size</span>(SelCh,<span class="number">1</span>);</span><br><span class="line">    [TobjV,index]=<span class="built_in">sort</span>(ObjV);</span><br><span class="line">    Chrom=[Chrom(index(<span class="number">1</span>:NIND-NSel),:);SelCh];</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure></p>
<h2 id="反转-不必要掌握"><a href="#反转-不必要掌握" class="headerlink" title="反转(不必要掌握)"></a>反转(不必要掌握)</h2><p>反转操作是针对TSP问题对于局部的一种优化,本身不在遗传算法范围内.这里给出算法代码.<br><figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SelCh</span>=<span class="title">Reverse</span><span class="params">(SelCh,D)</span></span></span><br><span class="line">    [row,col]=<span class="built_in">size</span>(SelCh);</span><br><span class="line">    ObjV=PathLength(D,SelCh);</span><br><span class="line">    SelCh1=SelCh;</span><br><span class="line">    <span class="keyword">for</span> <span class="built_in">i</span>=<span class="number">1</span>:row</span><br><span class="line">        r1=randsrc(<span class="number">1</span>,<span class="number">1</span>,[<span class="number">1</span>:col]);</span><br><span class="line">        r2=randsrc(<span class="number">1</span>,<span class="number">1</span>,[<span class="number">1</span>:col]);</span><br><span class="line">        mininverse=<span class="built_in">min</span>([r1 r2]);</span><br><span class="line">        maxinverse=<span class="built_in">max</span>([r1 r2]);</span><br><span class="line">        SelCh1(<span class="built_in">i</span>,mininverse:maxinverse)=SelCh1(<span class="built_in">i</span>,maxinverse:<span class="number">-1</span>:mininverse);</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    ObjV1=PathLength(D,SelCh1);</span><br><span class="line">    index=ObjV1&lt;ObjV;</span><br><span class="line">    SelCh(index,:)=SelCh1(index,:);</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure></p>
<h1 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h1><p>遗传算法是一个模拟生物遗传进化的,比较成熟的大型智能算法.采用设计好的算子,可以解决大部分类型的规划问题.但由于其算法较为复杂,在比赛中没有充分把握还是要谨慎使用.<br>本文借助三个案例,大致介绍了遗传算法的工作原理,同时对两大典型的规划问题给出了简单可调用的函数原型.方便大家学习使用.<br>同时,遗传算法的优劣总结如下(个人观点):</p>
<h2 id="优点"><a href="#优点" class="headerlink" title="优点"></a>优点</h2><ol>
<li>相对于新型的智能算法,如:粒子群算法,蚁群算法.他更加成熟稳定.这表现在可适用的问题类型众多(蚁群不能算TSP).</li>
<li>相对于模拟退火算法,它不用给出初始值和重组解的方式,而是交给算法本身完成.使用时只需给定目标函数和解的限制条件.</li>
<li>相对于模拟退火,它有更优秀的收敛时间,可控的时间复杂度.并在连续型随机变量上有明显优势.</li>
<li>相对于传统算法,有一定的定制空间,自己定制的目标函数能适用于matlab的各种函数(包括给神经网络做优化).</li>
</ol>
<h2 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h2><ol>
<li>相对于新型智能算法,它收敛速度和结果差强人意.</li>
<li>相对于能够定制解的模拟退火,遗传算法不够灵活.</li>
<li>整体算法实现复杂,且由于算子众多,学习成本大.若在比赛中不能将问题转化成文中介绍的两种类型,不建议使用该算法.</li>
</ol>
<p>参考书籍:《MATLAB智能算法30个案例分析》<br>程序下载: <a href="https://github.com/Anemone95/matlab-GA" target="_blank" rel="noopener">https://github.com/Anemone95/matlab-GA</a></p>

    </div>

    
    
    
        
      
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Anemone</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://anemone.top/数模-遗传算法——另一个求最优解的智能算法/" title="遗传算法——另一个求最优解的智能算法">http://anemone.top/数模-遗传算法——另一个求最优解的智能算法/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！</li>
</ul>
</div>

      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/算法/" rel="tag"># 算法</a>
            
              <a href="/tags/人工智能/" rel="tag"># 人工智能</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/数模-模拟退火——史上最简单的智能算法/" rel="next" title="模拟退火——史上最简单的智能算法">
                  <i class="fa fa-chevron-left"></i> 模拟退火——史上最简单的智能算法
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/数模-神经网络——数值分析问题的最后杀手锏/" rel="prev" title="神经网络——数值分析问题的最后杀手锏">
                  神经网络——数值分析问题的最后杀手锏 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          
    
    <div class="comments" id="gitalk-container"></div>
  

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#快速使用"><span class="nav-number">2.</span> <span class="nav-text">快速使用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#连续型随机变量"><span class="nav-number">2.1.</span> <span class="nav-text">连续型随机变量</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#原理讲解"><span class="nav-number">3.</span> <span class="nav-text">原理讲解</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#连续型随机变量-TSP问题"><span class="nav-number">3.1.</span> <span class="nav-text">连续型随机变量(TSP问题)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#初始化种群"><span class="nav-number">3.2.</span> <span class="nav-text">初始化种群</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#适应度函数"><span class="nav-number">3.3.</span> <span class="nav-text">适应度函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#选择操作"><span class="nav-number">3.4.</span> <span class="nav-text">选择操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#交叉操作"><span class="nav-number">3.5.</span> <span class="nav-text">交叉操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#变异操作"><span class="nav-number">3.6.</span> <span class="nav-text">变异操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重组"><span class="nav-number">3.7.</span> <span class="nav-text">重组</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#反转-不必要掌握"><span class="nav-number">3.8.</span> <span class="nav-text">反转(不必要掌握)</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#小结"><span class="nav-number">4.</span> <span class="nav-text">小结</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#优点"><span class="nav-number">4.1.</span> <span class="nav-text">优点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#缺点"><span class="nav-number">4.2.</span> <span class="nav-text">缺点</span></a></li></ol></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="/images/avatar.jpg"
      alt="Anemone">
  <p class="site-author-name" itemprop="name">Anemone</p>
  <div class="site-description" itemprop="description">关注Web安全、移动安全、Fuzz测试和机器学习</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">70</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        <span class="site-state-item-count">31</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="feed-link motion-element">
    <a href="/atom.xml" rel="alternate">
      <i class="fa fa-rss"></i>RSS
    </a>
  </div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/anemone95" title="GitHub &rarr; https://github.com/anemone95" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="mailto:anemone95@qq.com" title="E-Mail &rarr; mailto:anemone95@qq.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
    
  </div>
  <div class="cc-license motion-element" itemprop="license">
    
  
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 – <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">anemone</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.9.0</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.4.0</div>

        






  
  <script>
  function leancloudSelector(url) {
    return document.getElementById(url).querySelector('.leancloud-visitors-count');
  }
  if (CONFIG.page.isPost) {
    function addCount(Counter) {
      var visitors = document.querySelector('.leancloud_visitors');
      var url = visitors.getAttribute('id').trim();
      var title = visitors.getAttribute('data-flag-title').trim();

      Counter('get', `/classes/Counter?where=${JSON.stringify({ url })}`)
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length > 0) {
            var counter = results[0];
            Counter('put', '/classes/Counter/' + counter.objectId, { time: { '__op': 'Increment', 'amount': 1 } })
              .then(response => response.json())
              .then(() => {
                leancloudSelector(url).innerText = counter.time + 1;
              })
            
              .catch(error => {
                console.log('Failed to save visitor count', error);
              })
          } else {
              Counter('post', '/classes/Counter', { title: title, url: url, time: 1 })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.log('Failed to create', error);
                });
            
          }
        })
        .catch(error => {
          console.log('LeanCloud Counter Error', error);
        });
    }
  } else {
    function showTime(Counter) {
      var visitors = document.querySelectorAll('.leancloud_visitors');
      var entries = [...visitors].map(element => {
        return element.getAttribute('id').trim();
      });

      Counter('get', `/classes/Counter?where=${JSON.stringify({ url: { '$in': entries } })}`)
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length === 0) {
            document.querySelectorAll('.leancloud_visitors .leancloud-visitors-count').forEach(element => {
              element.innerText = 0;
            });
            return;
          }
          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.url;
            var time = item.time;
            leancloudSelector(url).innerText = time;
          }
          for (var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = leancloudSelector(url);
            if (element.innerText == '') {
              element.innerText = 0;
            }
          }
        })
        .catch(error => {
          console.log('LeanCloud Counter Error', error);
        });
    }
  }

  fetch('https://app-router.leancloud.cn/2/route?appId=o5UaCJdPfEG0g7MVxXSMagpT-gzGzoHsz')
    .then(response => response.json())
    .then(({ api_server }) => {
      var Counter = (method, url, data) => {
        return fetch(`https://${api_server}/1.1${url}`, {
          method: method,
          headers: {
            'X-LC-Id': 'o5UaCJdPfEG0g7MVxXSMagpT-gzGzoHsz',
            'X-LC-Key': 'c6IN1PuMV3QPltJcrHfn74Gt',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      if (CONFIG.page.isPost) {
        const localhost = /http:\/\/(localhost|127.0.0.1|0.0.0.0)/;
        if (localhost.test(document.URL)) return;
        addCount(Counter);
      } else if (document.querySelectorAll('.post-title-link').length >= 1) {
        showTime(Counter);
      }
    });
  </script>






        
      </div>
    </footer>
  </div>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.1.0/lib/anime.min.js"></script>
  <script src="https://cdn.bootcss.com/velocity/1.2.1/velocity.min.js"></script>
  <script src="https://cdn.bootcss.com/velocity/1.2.1/velocity.ui.js"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>
<script src="/js/next-boot.js?v=7.4.0"></script>



  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>








  
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/instantsearch.js@2.10.4/dist/instantsearch.min.css">
<script src="//cdn.jsdelivr.net/npm/instantsearch.js@2.10.4/dist/instantsearch.min.js"></script><script src="/js/algolia-search.js?v=7.4.0"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.bootcss.com/mermaid/8.2.6/mermaid.min.js', () => {
    mermaid.initialize({
      theme: 'forest',
      logLevel: 3,
      flowchart: { curve: 'linear' },
      gantt: { axisFormat: '%m/%d/%Y' },
      sequence: { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>




  

  

  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID: 'f3075553d7b0225df6ca',
      clientSecret: '68362ba87c4cc8e13103afcf729f5bd8ea176a78',
      repo: 'anemone95.github.io',
      owner: 'Anemone95',
      admin: ['Anemone95'],
      id: '1b53ac7c7daad650696476e65f4dfa69',
        language: window.navigator.language || window.navigator.userLanguage,
      
      distractionFreeMode: 'true'
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
</script>

</body>
</html>
